<template>
  <div class="find-group">
    <div class="search-container">
      <van-icon
          name="arrow-left"
          size="20"
          class="back-button"
          @click="router.back()"
      />
      <!-- 搜索框 -->
      <van-search
          v-model="searchText"
          placeholder="搜索圈子名称"
          style="width: 100%"
          shape="round"
          @update:model-value="loadGroups"
      />
    </div>
    <!-- 圈子列表 -->
    <van-list>
      <div
          v-for="group in allGroups"
          :key="group.id"
          class="group-item"
          @click="handleItemClick(group.id)"
      >
        <van-image
            class="group-avatar"
            width="40"
            height="40"
            :src="group.avatar"
            alt="圈子头像"
        ></van-image>
        <div class="group-info">
          <h3>{{ group.name }}</h3>
          <p class="description">{{ group.description }}</p>
        </div>
        <van-button
            round
            size="small"
            :type="group.isFollowed ? 'default' : 'primary'"
            @click.stop="toggleFollow(group)"
        >
          {{ group.isFollowed ? '已关注' : '关注' }}
        </van-button>
      </div>
    </van-list>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { searchGroups, followGroup } from '@/api/index.js';
import {useRouter}  from "vue-router";

const router = useRouter();
const searchText = ref('');
const allGroups = ref([]);

// 获取所有圈子
const loadGroups = async () => {
  const res = await searchGroups(searchText.value);
  allGroups.value = res;
};

// 关注/取消关注
const toggleFollow = async (group) => {
  await followGroup(group.id);
  group.isFollowed = !group.isFollowed;
};

// 处理列表项点击
const handleItemClick = (id) => {
  router.push(`/groupDetail/${id}`)
}

onMounted(() => {
  loadGroups();
});
</script>

<style scoped>
.search-container {
  display: flex; /* 使用 Flexbox 布局 */
  align-items: center; /* 垂直居中对齐 */
  margin-left: 20px;
}

.back-button {
  margin-right: 10px; /* 设置返回按钮与搜索框之间的间距 */
}
.group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: white;
  margin: 8px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);

  .group-info {
    flex: 1;
    margin-right: 16px;

    h3 {
      margin: 0 0 8px 0;
      font-size: 16px;
    }

    .description {
      color: #666;
      font-size: 12px;
      margin: 4px 0;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
  }
}
</style>
